package uiml.android.executing;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.view.View;

import uiml.android.elements.IUimlAttribute;
import uiml.android.elements.Part;
import uiml.android.elements.Property;
import uiml.android.elements.UimlElement;
import uiml.android.elements.peers.Vocabulary;

public class Param extends UimlElement implements IUimlAttribute{
	
	// TODO comment
	private String name = "";
	
	// TODO comment
	public final static String IAM 	= "param";
	public final static String NAME = "name";
	
	private String value = null;
	private Object subParam = null;

	
	/**
	 * 
	 * @param node
	 */
	public Param(Element node) {
		super(node);
		process();
	}
	
	/**
	 * 
	 */
	@Override
	public void process() {
		processAttributes();
		
		NodeList childItems = node.getChildNodes();

		if(childItems != null) {
			
			for(int i=0; i<childItems.getLength(); ++i) {
				Node child = childItems.item(i);	
				if(child.getNodeType() == Node.ELEMENT_NODE)
					processElement((Element)child);
			}
			
			if(subParam == null && childItems.getLength() == 1)
				value = node.getFirstChild().getNodeValue();
		}	
	}
	
	/**
	 * 
	 */
	public void processElement(Element elem) {	
		if(elem.getTagName().equals(Property.IAM))
			subParam = new Property(elem);
	}

	@Override
	public void processAttributes() {
		NamedNodeMap attributes = node.getAttributes();
		
		if(attributes != null) {
			if(attributes.getNamedItem(NAME) != null)
				setName(attributes.getNamedItem(NAME).getNodeValue());
		}
		
	}
	
	public Object execute(View invoker, Part subTree, Vocabulary voc) {
		
		Object result = null;
		
		if(value != null)
			result = (Object)value;
		if(subParam != null) {
			if(subParam.getClass().equals(Property.class))
				result = ((Property)subParam).executeGetProperty(invoker, subTree, voc);
		}
			
		return result;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	

}
